package get

import (
	"database/sql"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Get_student(r *gin.Engine) {
	var db *sql.DB
	var err error
	var sno, name, password, level, gender, age, dept, class string = "0", "0", "0", "0", "0", "0","0" ,"0"

	db, err = sql.Open("postgres", "port=5432 user=postgres password=system dbname=databasedesign sslmode=disable")
	if err != nil {
		panic(err)
	}
	
		// 获取搜索
		r.GET("/getstudent", func(c *gin.Context) {
			xx := c.Query("xx")
			if xx != "" {
	
				str := "SELECT * FROM student where sno='" + xx + "'"
				rows, err := db.Query(str)
				if err != nil {
					panic(err)
				}
	
				for rows.Next() {
	
					err = rows.Scan(&sno, &name, &password, &level, &gender, &age, &dept, &class)
					if err != nil {
						panic(err)
					}
	
					c.JSON(200, gin.H{
						"sno":     sno,
						"name":   name,
						"password": password,
						"level":    level,
						"gender":   gender,
						"age":		age,
						"dept":		dept,
						"class":     class,
					})
				}
			}
	
		})
	
		// 添加用户
		r.GET("/insertstudent", func(c *gin.Context) {
			sno = c.Query("sno")
			name = c.Query("name")
			password = c.Query("password")
			level = c.Query("level")
			gender = c.Query("gender")
			age = c.Query("age")
			dept = c.Query("dept")
			class = c.Query("class_sql")
			if err != nil {
				panic(err)
			}
			str := "INSERT INTO student(sno,name,password,level,gender,age,dept,class) VALUES($1,$2,$3,$4,$5,$6,$7,$8)"
			stmt, err := db.Prepare(str)
			if err != nil {
				panic(err)
			}
	
			res, err := stmt.Exec(sno,name,password,level,gender,age,dept,class)
			if err != nil {
				panic(err)
			}
	
			affect, err := res.RowsAffected()
			if err != nil {
				panic(err)
			}
	
			fmt.Println("rows affect:", affect)
		})
	
		//修改数据
		r.GET("/updatestudent", func(c *gin.Context) {
			sno = c.Query("sno")
			name = c.Query("name")
			password = c.Query("password")
			level = c.Query("level")
			gender = c.Query("gender")
			age = c.Query("age")
			dept = c.Query("dept")
			class = c.Query("class_sql")
	
			str := "update student set name=$1,password=$2,level=$3,gender=$4,age=$5,dept=$6,class=$7, where sno=$8"
			stmt, err := db.Prepare(str)
			if err != nil {
				panic(err)
			}
	
			res, err := stmt.Exec(name, password, level, gender, age, dept, class, sno)
			if err != nil {
				panic(err)
			}
	
			affect, err := res.RowsAffected()
			if err != nil {
				panic(err)
			}
	
			fmt.Println("rows affect:", affect)
		})
	
		//删除用户
		r.GET("/deletestudent", func(c *gin.Context) {
			sno = c.Query("sno")
	
			if err != nil {
				panic(err)
			}
	
			stmt, err := db.Prepare("delete from student where sno=$1")
			if err != nil {
				panic(err)
			}
	
			res, err := stmt.Exec(sno)
			if err != nil {
				panic(err)
			}
	
			affect, err := res.RowsAffected()
			if err != nil {
				panic(err)
			}
	
			fmt.Println(" Delete : rows affect:", affect)
		})
	}